package xcmg.device.web.barcode;

import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.infra.interceptor.externalApiCheck.handle.ApiCheckStrategy;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.barcode.BarcodeService;
import xcmg.device.service.vo.barcode.BarCodeCheckView;
import xcmg.device.service.vo.barcode.BarcodeManageVO;
import xcmg.device.service.vo.barcode.BatchPrintVO;
import xcmg.device.service.vo.barcode.BindBarCodeVO;
import xcmg.device.service.vo.barcode.SinglePrintVO;
import xcmg.device.service.vo.barcode.SplitNumVO;
import xcmg.device.service.vo.barcode.SplitPrintVO;
import xcmg.device.service.warehouse.WarehouseInventoryService;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by sqq on 2018/1/25.
 */
@RestController
@RequestMapping("/barcode")
public class BarcodeController extends BasicController {

    @Autowired
    private BarcodeService barcodeService;
    @Autowired
    private ExternalParamCheckService externalParamCheckService;

    @Autowired
    private WarehouseInventoryService warehouseInventoryService;
    // 塔机的sapCode,写死用来获取塔机的组织机构编码
    private static final String TJ_SAP_CODE = "2130";

    //条码管理-条码包装条码单个打印
    @RequestMapping(value = "/singlePrint", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult singlePrint(@RequestBody SinglePrintVO singlePrintVO) throws Exception {
        List<BarcodeManageVO> results = barcodeService.singlePrint(singlePrintVO, getUserId(), getOrgId());
        return actionResult(singlePrintVO.getErrorCode(), results);
    }

    //条码管理-条码包装生成条码（复选框多选批量生成）
    @RequestMapping(value = "/batchPrintForSelect", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult batchPrintForSelect(@RequestBody List<BatchPrintVO> list) throws Exception {
        List<BarcodeManageVO> results = barcodeService.batchPrintForSelect(list, getUserId(), getOrgId());
        return actionResult(ErrorCode.Success, results);
    }

    //采购订单列表生成条码
    @RequestMapping(value = "/singlePurchasePrint", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult singlePurchasePrint(@RequestBody SinglePrintVO singlePrintVO) throws Exception {
        List<BarcodeManageVO> results = barcodeService.singlePurchasePrint(singlePrintVO, getUserId(), getOrgId());
        return actionResult(singlePrintVO.getErrorCode(), results);
    }

    @RequestMapping(value = "/batchPrint", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult batchPrint(@RequestBody List<BatchPrintVO> batchPrintVOList) throws Exception {
        List<BarcodeManageVO> results = barcodeService.batchPrint(batchPrintVOList, getUserId(), getOrgId());
        return actionValueResult(results);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<BarcodeManageVO> condtion) throws Exception {
        BarcodeManageVO barcodeManageVO = condtion.getFilters();
        if (barcodeManageVO == null) {
            barcodeManageVO = new BarcodeManageVO();
        }
        barcodeManageVO.setOrgId(getOrgId());
        condtion.setFilters(barcodeManageVO);
        PageCommonVO pageCommonVO = barcodeService.list(condtion);
        return actionValueResult(pageCommonVO.getPageInfo());
    }

    @RequestMapping(value = "/updatePrintCount", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult updatePrintCount(@RequestBody BarcodeManageVO barcodeManageVO) throws Exception {
        ErrorCode code = barcodeService.updatePrintCount(barcodeManageVO.getBarcodes(), getUserId(), getOrgId());
        return actionResult(code);
    }

    @RequestMapping(value = "/updateBatchIdAndSupplier", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult updateBatchId(@RequestBody BarcodeManageVO barcodeManageVO) throws Exception {
        ErrorCode code = barcodeService.updateBatchId(barcodeManageVO, getUserId(), getOrgId());
        return actionResult(code);
    }

    //拆箱打印
    @RequestMapping(value = "/splitPrint", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult splitPrint(@RequestBody SplitPrintVO splitPrintVO) throws Exception {
        try {
            List<BarcodeManageVO> result = barcodeService.splitPrint(splitPrintVO, getUserId(), getOrgId());
            return actionResult(splitPrintVO.getCode(), result);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/splitNum", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult splitNum(@RequestBody SplitNumVO splitNumVO) throws Exception {
        try {
            BarcodeManageVO result = barcodeService.splitNum(splitNumVO, getUserId(), getOrgId());
            return actionResult(splitNumVO.getCode(), result);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/item", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String barcode) throws Exception {
        BarcodeManageVO barcodeManageVO = barcodeService.item(barcode, getOrgId());
        return actionValueResult(barcodeManageVO);
    }


    @ApiOperation(value = "提供给塔机的二维码查询外部接口")
    @ExternalApiRequest(ApiCheckStrategy.ApiCheckOptionEnum.OPTION_SECRET)
    @RequestMapping(value = "/item4TJ", method = RequestMethod.GET)
    public ActionResult item4TJ(String barcode) throws Exception {
        LogHelper.monitor("塔机查询条码信息参数：" + barcode.toString());
        String orgId = externalParamCheckService.getOrgIdBySapCode(TJ_SAP_CODE);
        BarcodeManageVO barcodeManageVO = barcodeService.item(barcode, orgId);
        ActionResult actionResult = barcodeService.item4TjCheck(barcodeManageVO, orgId);
        return actionResult;
    }

//    @RequestMapping(value = "/checkBarcode", method = RequestMethod.POST)
//    public ActionResult checkBarcode(@RequestBody BarcodeManageVO barcodeManageVO) throws Exception {
//        return actionResult(barcodeService.checkBarcode(barcodeManageVO.getBarcode()));
//    }

//    @RequestMapping(value = "/qrCode", method = RequestMethod.GET)
//    public ActionResult qrCode(@RequestParam("urles") List<String> urles,
//        @RequestParam(value="width", required = false, defaultValue = "400") int width,
//        @RequestParam(value="height", required = false, defaultValue = "400")int height,
//        @RequestParam(required = false) String logoPath)throws Exception{
//        List<String> qrCodeImages = new ArrayList<>();
//        for(String url: urles) {
//            qrCodeImages.add(QRCodeUtil.generalQRCode(url,width,height,logoPath));
//        }
//        return actionResult(qrCodeImages);
//    }

//    @RequestMapping(value = "/qrCode", method = RequestMethod.POST)
//    public ActionResult qrCode2(@RequestBody QrCodeParamVO paramVO) throws Exception {
//        List<String> qrCodeImages = new ArrayList<>();
//        if (null == paramVO || CollectionUtils.isEmpty(paramVO.getUrles())) {
//            return new ActionResult(ErrorCode.IllegalArument);
//        }
//        for (String url : paramVO.getUrles()) {
//            qrCodeImages.add(QRCodeUtil.generalQRCode(url, paramVO.getWidth(), paramVO.getHeight(), paramVO.getLogoPath()));
//        }
//        return actionResult(qrCodeImages);
//    }


    @RequestMapping(value = "/listForLJ", method = RequestMethod.GET)
    public ActionResult listForLJ(String barcode) throws Exception {
        return actionValueResult(barcodeService.listForLJ(barcode, getOrgId()));
    }

    //条码管理-包装条码直投打印
    @RequestMapping(value = "/singleDirectPrint", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult singleDirectPrint(@RequestBody SinglePrintVO singlePrintVO) {
        if (null == singlePrintVO || CollectionUtils.isEmpty(singlePrintVO.getDetailList())) {
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            int totalSize = null == singlePrintVO.getTotalSize() || singlePrintVO.getTotalSize() <= 0 ? 1 : singlePrintVO.getTotalSize();
            totalSize = totalSize > 1000 ? 1000 : totalSize;
            int listSize = totalSize * (singlePrintVO.getDetailList().size() + 1);
            if (listSize > 10000) {
                return actionResult(ErrorCode.IllegalArument, "条码总数量超过10000不允许生成条码，当前数量：" + listSize, null);
            }
            List<BarcodeManageVO> r = new ArrayList<>(listSize);
            for (int i = 0; i < totalSize; i++) {
                r.addAll(barcodeService.singleDirectPrint(singlePrintVO, getUserId(), getOrgId()));
            }
            return actionValueResult(r);
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/directPrintExport", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void directPrintExport(@RequestParam("materialsNo") String materialsNo,
                                  @RequestParam("totalQty") BigDecimal totalQty,
                                  @RequestParam("detailListStr") String detailListStr) throws Exception {
        barcodeService.directPrintExport(materialsNo, totalQty, detailListStr, getUserId(), getOrgId());
    }

    @RequestMapping(value = "/directPrintExportBatch", method = RequestMethod.POST)
    public void directPrintExport(@RequestParam("materialsNo") String materialsNo,
                                  @RequestParam("totalQty") BigDecimal totalQty,
                                  @RequestParam("totalSize") Integer totalSize,
                                  @RequestParam("detailListStr") String detailListStr) throws Exception {
        barcodeService.directPrintExportBatch(materialsNo, totalQty, totalSize, detailListStr, getUserId(), getOrgId());
    }

//    @RequestMapping(value = "/pullInfos", method = RequestMethod.POST)
//    @ApiOperation(value = "从ERP拉取条码信息")
//    @FastMappingInfo(needLogin = true)
//    public ActionResult pullInfos(@RequestBody BarcodePullCondition barcodePullCondition) throws Exception {
//        barcodeService.setPullRecord();
//        barcodeService.manualPullInfos(barcodePullCondition);
//        return actionResult(ErrorCode.Success);
//    }

    @RequestMapping(value = "/bindBarcode", method = RequestMethod.POST)
    @ApiOperation(value = "绑定单号")
    @FastMappingInfo(needLogin = true)
    public ActionResult bindBarcode(@RequestBody BindBarCodeVO bindBarCodeVO) throws Exception {
        return actionResult(barcodeService.bindBarcode(bindBarCodeVO, getOrgId()));
    }

    @RequestMapping(value = "/barCodeCheck", method = RequestMethod.GET)
    @ApiOperation(value = "管理端查看条码真伪")
    public ActionResult<BarCodeCheckView> barCodeCheck(@RequestParam(value = "barCode", required = true) String barCode) {
        String userId = getUserId();
        BarCodeCheckView result = barcodeService.queryBarCodeCheck(barCode, userId, false);
        return actionValueResult(result);
    }
}
